package com.party.business;

/**
 * @author: zhaoyongke
 * @create: 2025-06-25 09:22
 * @description: 22
 */
import com.party.business.domain.FieldShow;
import com.party.business.service.IFieldShowService;
import com.party.common.annotation.Excel;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class FieldReflectionUtil {

    private final IFieldShowService fieldShowService;

    public FieldReflectionUtil(IFieldShowService fieldShowService) {
        this.fieldShowService = fieldShowService;
    }

    /**
     * 反射获取类的字段和注释，并插入到数据库中
     *
     * @param clazz    需要处理的类类型
     * @param tableId  字段所属的表名或唯一标识符
     */
    public void insertFieldsToDatabase(Class<?> clazz, String tableId) {
        Field[] fields = clazz.getDeclaredFields();

        List<FieldShow> fieldShows = new ArrayList<>();

        for (Field field : fields) {
            // 获取字段名称
            String columnName = field.getName();

            // 获取字段注释（假设使用了 @Excel 注解）
            Excel excelAnnotation = field.getAnnotation(Excel.class);
            String columnComment = (excelAnnotation != null && StringUtils.isNotBlank(excelAnnotation.name()))
                    ? excelAnnotation.name()
                    : "未知注释";

            // 构建 FieldShow 对象
            FieldShow fieldShow = new FieldShow();
            fieldShow.setTableId(tableId);         // 表名或表ID
            fieldShow.setColumnName(columnComment); // 字段注释
            fieldShow.setColumnKey(columnName);     // 字段名称
            fieldShow.setIsVisible(1);
            fieldShow.setId(UUID.randomUUID().toString());// 默认可见
            fieldShowService.insertFieldShow(fieldShow);
        }

    }
}

